package com.tangguo.vshop.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tangguo.vshop.domain.OrderItem;
import com.tangguo.vshop.domain.Product;
import com.tangguo.vshop.domain.Shoppingcart;
import com.tangguo.vshop.repository.ProductRepository;
import com.tangguo.vshop.repository.ShoppingCartRepository;
import com.tangguo.vshop.security.JwtUser;
/**
 * 商品信息
 * @author doonly
 *
 */
@RestController
@RequestMapping("/product")
public class ProductController {
	@Autowired
	private ProductRepository productRepository;
	@Autowired
	private ShoppingCartRepository shoppingCartRepository;

	@RequestMapping("/search/{customerId}")
	public Page<Product> search(String keywords,@PathVariable("customerId")String customerId,Pageable pageable){
		JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Page<Product> productPage  = null;
		if(keywords==null||"".equals(keywords)){
			productPage = productRepository.findAll(pageable);
		}else{
			productPage = productRepository.findByHelpcodeLikeOrNameLike(keywords,keywords,pageable);
		}
		Shoppingcart cart = shoppingCartRepository.findByCreatorAndCustomer(jwtUser.getId(), customerId);
		initProductPage(productPage,cart);
		return productPage;

	}

	private void initProductPage(Page<Product> productPage, Shoppingcart cart) {
		for(Product product:productPage.getContent()){
			product.setCartPrice(product.getPrice());
			if(cart!=null){
				OrderItem item = getOrderItem(product,cart.getOrderDetails());
				if(item==null) continue;
				product.setCartPrice(item.getPrice());
				product.setCartQty(item.getQty());
			}
		}
	}

	private OrderItem getOrderItem(Product product, List<OrderItem> orderDetails) {
		for(OrderItem item:orderDetails){
			if(item.getProduct().getId().equals(product.getId())){
				return item;
			}
		}
		return null;
	}

}
